<script setup lang="ts">
  import SchemaSearchPage from '@/components/schema-search-page/index.vue'
  import type { DoSearch, SearchFieldTypes } from '@/components/schema-search-page/interface'
  import { useDishCategory } from '@/datas/use-dish-category'
  import { CategoryTypeEnum, DishStatusEnum } from '@/shared'
  import type { CategoryEntity } from '@/shared/entity/category'
  import type { DishEntity } from '@/shared/entity/dish'
  import { DishStatusOptions } from '@/shared/options'
  import { getUri } from '@/utils'
  import { DoDelete, DoGet, DoPost } from '@/utils/http'
  import { Message } from '@arco-design/web-vue'
  import { computed, ref, useTemplateRef, type ComputedRef } from 'vue'
  import Create from './create.vue'

  const tableRef = useTemplateRef('tableRef')

  const selectedKeys = ref<number[]>([])

  const { data } = useDishCategory(CategoryTypeEnum.Dish)

  const Refresh = () => {
    tableRef.value?.Refresh()
  }

  const categoryOptions = computed(() =>
    data.value?.data?.map(item => ({
      label: item.name,
      value: item.id
    }))
  )

  const searchFields: ComputedRef<SearchFieldTypes> = computed(() => [
    {
      type: 'Input',
      fieldName: 'name',
      fieldLabel: '菜品名称',
      props: {
        style: 'width: 208px'
      }
    },
    {
      type: 'Select',
      fieldName: 'categoryId',
      fieldLabel: '菜品分类',
      props: {
        options: categoryOptions.value,
        style: 'width: 208px'
      }
    },
    {
      type: 'Select',
      fieldName: 'status',
      fieldLabel: '售卖状态',
      props: {
        options: DishStatusOptions,
        style: 'width: 208px'
      }
    }
  ])

  const columns = [
    {
      title: '菜品名称',
      dataIndex: 'name'
    },
    {
      title: '图片',
      dataIndex: 'image'
    },
    {
      title: '菜品分类',
      dataIndex: 'categoryId'
    },
    {
      title: '售价',
      dataIndex: 'price'
    },
    {
      title: '售卖状态',
      dataIndex: 'status'
    },
    {
      title: '最后操作时间',
      dataIndex: 'updateTime'
    },
    {
      title: '操作',
      dataIndex: 'action'
    }
  ]

  const doSearch: DoSearch = async (page: number, size: number, conditions?: any) => {
    const resp = await DoGet<DishEntity[]>(
      getUri('/dish/page', {
        page,
        size,
        ...conditions
      })
    )

    return {
      data: resp.data,
      total: resp.total || 0
    }
  }
  const visible = ref(false)

  const id = ref<number>()

  const handlerDeleteBatch = async () => {
    if (selectedKeys.value.length) {
      await DoDelete(
        getUri('/dish', {
          ids: selectedKeys.value
        })
      )
      Message.success('删除成功')
      Refresh()
    }
  }

  const handlerDelete = async (id: number) => {
    await DoDelete(
      getUri('/dish', {
        ids: id
      })
    )
    Message.success('删除成功')
    Refresh()
  }

  const handlerChangeStatus = async (status: DishStatusEnum, id: number) => {
    await DoPost(
      getUri(`/dish/status/${status}`, {
        id
      })
    )
    Refresh()
  }

  const clear = () => {
    id.value = undefined
  }
</script>

<template>
  <SchemaSearchPage
    :search-fields="searchFields"
    :columns="columns"
    :do-search="doSearch"
    ref="tableRef"
    :table="{
      rowKey: 'id',
      rowSelection: {
        type: 'checkbox',
        showCheckedAll: true
      }
    }"
    v-model:selected-keys="selectedKeys"
  >
    <template #image="{ record }">
      <div class="dish-img">
        <img :src="record.image" alt="" />
      </div>
    </template>
    <template #categoryId="{ record }">
      {{ categoryOptions?.find(item => item.value === record.categoryId)?.label }}
    </template>
    <template #price="{ record }">¥{{ record.price }}</template>
    <template #status="{ record }">
      {{ DishStatusOptions.find(item => item.value === record.status)?.label }}
    </template>
    <template #action="{ record }">
      <a-space>
        <a-link
          @click="
            () => {
              visible = true
              id = record.id
            }
          "
        >
          修改
        </a-link>
        <a-popconfirm content="确认删除吗？" @ok="() => handlerDelete(record.id)">
          <a-link status="danger">删除</a-link>
        </a-popconfirm>
        <a-popconfirm
          content="确认操作吗？"
          @ok="
            handlerChangeStatus(
              record.status === DishStatusEnum.Enable
                ? DishStatusEnum.Disable
                : DishStatusEnum.Enable,
              record.id
            )
          "
        >
          <a-link>{{ record.status === DishStatusEnum.Disable ? '启售' : '停售' }}</a-link>
        </a-popconfirm>
      </a-space>
    </template>
    <template #default>
      <a-space>
        <a-button type="primary" @click="handlerDeleteBatch" :disabled="!selectedKeys.length">
          批量删除
        </a-button>
        <a-button
          type="primary"
          @click="
            () => {
              visible = true
              id = undefined
            }
          "
        >
          新增菜品
        </a-button>
      </a-space>
    </template>
  </SchemaSearchPage>
  <Create v-model="visible" :id="id" @refresh="Refresh" @clear="clear" />
</template>

<style lang="less" scoped>
  .dish-img {
    width: 100px;
    height: 100px;
    > img {
      width: 100%;
      height: 100%;
    }
  }
</style>
